<template>
  <div>
    <myDivider :name="name"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>

    <div class="box">
      <!-- 车位信息导入需要选择小区 -->
      <div v-if="name == '车位信息导入'" style="display: flex;align-items: center;margin-left: 40px;margin-top: 40px;">
        <el-button type="primary" style="margin-right: 10px" @click="toSelect('小区')">选择小区</el-button>
        <el-input style="width: 280px;" v-model="residentialName" disabled placeholder="请选择所属小区"></el-input>
      </div>

      <div class="uploadBox" style="margin-left: 40px;margin-top: 40px;width: 500px;">
        <!-- 上传按钮 -->
        <el-upload ref="upload" action="#" auto-upload :multiple="false" accept=".xlsx" :http-request="submitUpload"
          list-type="text" :before-upload="beforeUpload" :show-file-list="false">
          <el-button @click="btnEvent" type="primary" icon="el-icon-upload">批量上传</el-button>
        </el-upload>
        <el-card shadow="never" v-if="uploadScene !== 'not'" style="margin-top: 20px;">
          <!-- 导入状态 -->
          <div class="uploadStateBox">
            <div class="uploadStateBox_top">
              <div class="topIcon">
                <!-- 上传中 -->
                <div v-if="uploadScene === 'ing'">
                  <el-progress :width="50" :stroke-width="10" type="circle" :percentage="percentage"></el-progress>
                </div>
                <!-- 上传失败 -->
                <i v-if="uploadScene === 'err'" class="el-icon-error" style="font-size: 50px;color: red;"></i>
                <!-- 上传成功-->
                <i v-if="uploadScene === 'ok'" class="el-icon-success" style="font-size: 50px;color: #67c23a;"></i>
              </div>
              <el-divider direction="vertical"></el-divider>
              <div class="topState">
                <span :style="{ color: uploadScene === 'ing' ? '#66b1ff' : uploadScene === 'ok' ? '#67c23a' : 'red' }">
                  {{ uploadScene === 'ing' ? '导入中' : uploadScene === 'ok' ? '导入成功' : '导入失败' }}
                </span>
              </div>
            </div>
            <el-divider></el-divider>
            <div v-if="errTitle != ''" class="uploadStateBox_bottom"
              style="max-height: 200px;overflow-y: scroll;margin-top: 10px;">
              <span v-html="errTitle"></span>
            </div>
          </div>
        </el-card>

      </div>

      <!-- 提示卡片 -->
      <el-card class="card" shadow="hover">
        <div>
          <div style="margin: 10px 0;">
            <span style="color: red;">* </span><span style="font-weight: 600;">请严格按照数据模板格式导入数据</span>
          </div>
          <div style="display: flex;align-items: center;">
            <img style="height:30px;width: 30px;" src="@/assets/xlsxwenjian.png" alt="">
            <el-button type="primary" style="margin-left: 10px;" @click="dow">点击下载模版文件</el-button>
          </div>
        </div>
        <div>
          <div style="margin: 10px 0;">
            <span style="color: red;">* </span><span style="font-weight: 600;">导入数据注意事项</span>
          </div>
          <div style="display: flex;flex-direction: column;font-size: 15px;">
            <span>1.支持文件类型：xlsx</span>
            <span>2.支持文件大小：1MB以内</span>
            <span>3.导入数据失败时，会显示错误数据，请进行修改再次上传</span>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 选择弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" title="选择归属小区"
      :visible.sync="selectShow">
      <el-divider></el-divider>
      <div style="display: flex;justify-content: space-between;margin: 20px 0;align-items: center;">
        <el-cascader @change="getSelectCellData" style="width: 200px;" clearable v-model="selectPopKeyCode"
          :options="selectPopKeyCodeData" :props="props" placeholder="请选择地区"></el-cascader>
        <el-input size="medium" style="width: 200px;" v-model="selectPopKeyCellName" placeholder="根据小区名称搜索"></el-input>
        <el-button size="medium" type="primary" @click="SelectSouSuo">查询</el-button>
      </div>
      <div class="popTableStyle">
        <el-table ref="selectTable" :data="selectData" style="width: 100%" height="300px" highlight-current-row>
          <el-table-column align="center" prop="areaName" label="地区">
          </el-table-column>
          <el-table-column align="center" prop="name" label="小区名称">
          </el-table-column>
        </el-table>
      </div>

      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectShow = false">取 消</el-button>
        <el-button type="primary" @click="selectOk">确
          定</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      percentage: 0,
      uploadScene: 'not', //批量导入上传状态 not未上传  ing上传中 err上传失败 ok上传成功
      errTitle: '',


      name: '',
      residentialId: null,
      buildingId: null,

      // 选择小区========
      props: {
        value: 'code',
        label: 'name'
      },
      residentialName: "",
      selectPopKeyCellName: '', //选择小区的筛选条件
      selectPopKeyCode: [],//选择小区的筛选条件
      selectPopKeyCodeData: [],
      selectData: [],
      selectShow: false,
      // ==========选择小区
    }
  },
  activated() {
    this.uploadScene = 'not'
    this.percentage = 0
    this.errTitle = ''


    this.name = this.$route.query.name
    if (this.name == '楼宇信息导入') {
      this.residentialId = this.$route.query.residentialId
    }
    if (this.name == '房间信息导入') {
      this.buildingId = this.$route.query.buildingId
    }
    if (this.name == '车位信息导入') {
      this.residentialId = ''
      this.residentialName = ''
    }
  },
  methods: {
    toSelect(name) {
      switch (name) {
        case '小区':
          this.selectShow = true
          this.selectPopKeyCellName = ''
          this.selectPopKeyCode = ''
          this.myGetRegionListForCarSpace()
          this.getSelectCellData()
          break
      }
    },
    SelectSouSuo() { //获取车主列表
      this.getSelectCellData()
    },
    async myGetRegionListForCarSpace() { //获取筛选项的地区列表
      let res = await this.$api.car.myGetRegionListForCarSpace()
      if (res.code == 200) {
        this.selectPopKeyCodeData = res.data
      } else {
        this.$message.error(res.message)
      }

    },
    async getSelectCellData() { //获取归属小区列表
      let res = await this.$api.car.myGetListForCarSpace({
        "name": this.selectPopKeyCellName, //非必填
        "code": this.selectPopKeyCode[this.selectPopKeyCode.length - 1] //非必填
      })
      console.log(res, '获取了归属小区');
      if (res.code == 200) {
        this.selectData = res.data
      } else {
        this.$message.error(res.message)
      }

      // 然后判断是否之前选中过，然后激活
      this.selectData.forEach((el, i) => {
        if (el.id == this.residentialId) {
          this.$nextTick(() => {
            this.$refs.selectTable.setCurrentRow(this.selectData[i])
          })
        }
      })
    },
    selectOk() {
      let data = this.$refs['selectTable'].store.states.currentRow
      if (data) {
        this.residentialId = data.id
        this.residentialName = data.name
        this.selectShow = false
      } else {
        this.$message.error('请选择归属小区')
      }

    },
    dow() { //下载模板
      const soa_account = sessionStorage.getItem("soa_account");
      const token = sessionStorage.getItem("soa_token")
      axios({
        method: 'get',
        url: defaultUrl+`/business/contract/downloadAnnex?filename=template/${this.name}模版.xlsx`,
        headers: {
          // 在这里添加自己需要的请求头
          account: soa_account,
          token: token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', this.name + '模版.xlsx')
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      })
    },
    // 上传附件之前
    beforeUpload(file) {
      this.percentage = 0
      // 判断是否含有特殊字符
      var pattern = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/; // 定义特殊字符的正则表达式模式
      if (pattern.test(file.name)) {
        this.$message.error('文件名称含有特殊字符,请修改后上传');
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error('附件大小不能超过 1MB!');
      }
      return isLt2M;
    },
    btnEvent(ev) {
      if (this.name == '车位信息导入') {
        if (this.residentialName) {

        } else {
          this.$message.error('请先选择小区，再批量上传')
          ev.stopPropagation();
        }
      } else {

      }

    },
    //上传文件
    async submitUpload(e) {

      this.uploadScene = 'ing'
      let soa_account = sessionStorage.getItem("soa_account");
      let token = sessionStorage.getItem("soa_token")
      let url;
      let formData = new FormData()
      switch (this.name) {
        case 'C端用户信息导入':
          url = '/appUser/importAppUser'
          formData.append('file', e.file)
          break
        case '人口信息导入':
          url = '/populationInformation/importUser'
          formData.append('file', e.file)
          break
        case '小区信息导入':
          url = '/residentialQuarters/importResidentialQuarters'
          formData.append('file', e.file)
          break
        case '机关信息导入':
          url = '/agency/importAgencyInfo'
          formData.append('file', e.file)
          break
        case '机构信息导入':
          url = '/company/importCompanyInfo'
          formData.append('file', e.file)
          break
        case '车位信息导入':
          url = '/parkingSpace/importParkingSpace'
          formData.append('file', e.file)
          formData.append('residentialId', this.residentialId)
          break
        case '楼宇信息导入':
          url = '/building/importBuilding'
          formData.append('file', e.file)
          formData.append('residentialId', this.residentialId)
          break
        case '房间信息导入':
          url = '/room/importRoom'
          formData.append('file', e.file)
          formData.append('buildingId', this.buildingId)
          break
          case '居民信息导入':
          url = '/customerRoomRelation/importCustomerRoomRelation'
          formData.append('file', e.file)
          break
      }

      axios({
        method: 'post',
        url: defaultUrl+'/business' + url, //此处为往后台发送请求的地址
        data: formData,
        headers: {
          token: token,
          account: soa_account
        },
        onUploadProgress: (e) => {      // 进度条
          this.percentage = Math.floor(
            (e.loaded / e.total) * 100,
          );
        }
      }).then(res => {
        if (res.data.code == 200) {

          if (res.data.data.result) {
            this.uploadScene = 'ok'
          } else {
            this.uploadScene = 'err'
          }
          this.errTitle = res.data.data.info
        } else {
          this.uploadScene = 'err'
          this.errTitle = res.data.message
        }
      })
        .catch(err => {
          this.uploadScene = 'err'
          this.errTitle = ''
        })
    },
  }
}
</script>

<style lang="less" scoped>
.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }
  }
}

.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.box {
  position: relative;

  .uploadBox {
    /deep/ .el-dialog {
      border-radius: 20px;

      .el-dialog__body {
        padding: 0 20px 30px 20px;

        .el-divider {
          margin: 20px 0;
        }
      }
    }

    /deep/ .upload-demo {

      &.opIcon {
        .el-upload--picture-card {
          display: none;
        }
      }
    }

    .uploadStateBox {

      ::-webkit-scrollbar {
        width: 2px !important;
        background-color: transparent;

        &-thumb {
          background-color: #939393;
        }
      }

      &_top {
        display: flex;
        align-items: center;
        // background: linear-gradient(to right, rgb(255, 255, 255), rgba(255, 0, 0, 0.55));

        .topIcon {}

        .topState {
          font-weight: 600;
          font-size: 20px;
        }
      }
    }
  }

  .card {
    position: absolute;
    top: 0;
    right: 20px;
    width: 400px;
    padding: 15px;
  }
}
</style>